//
//  StorageScene.m
//  SpaceStorm
//
//  Created by  mmj on 13-7-9.
//   [存储界面]
//
#import "Variable.h"

#import "ShipInfoMgr.h"
#import "StorageScene.h"
#import "BubbleSprite.h"
#import "UserData.h"
#import "UnitProxy.h"
#import "StartScene.h"
#import "LevelUpInfoMgr.h"
#import "ShipVo.h"

@implementation StorageItem

+(id) itemWithIndex:(int)index
{
    return [[[self alloc] initWithIndex:index] autorelease];
}

-(id) initWithIndex:(int)index
{
    if( (self=[super init]))
    {
        itemIndex = index;
        
        //纪录当前得item的key
        switch (itemIndex) 
        {
            case 1:
            {
                dataKey = USERDATA_KEY1;
                break;
            }
            case 2:
            {
                dataKey = USERDATA_KEY2;
                break;
            }
            case 3:
            {
                dataKey = USERDATA_KEY3;
                break;
            }
            default:
                dataKey = USERDATA_KEY1;
                break;
        }
        
        //第一个人物的信息
        ppFloor = [CCSprite spriteWithSpriteFrameName:@"storageFloor.png"];
        //新建存档
        newFloor = [CCSprite spriteWithSpriteFrameName:@"storageNewFloor.png"];
        
        
        //人物
        ppNewSaveNormal = [CCSprite spriteWithSpriteFrameName:@"storageNew.png"];
        ppNewSaveClick = [CCSprite spriteWithSpriteFrameName:@"storageNew.png"];
        ppLineNormal = [CCSprite spriteWithSpriteFrameName:@"storageNormal.png"];
        ppLineClick = [CCSprite spriteWithSpriteFrameName:@"storageClick.png"];
        ppReadNormal = [CCSprite spriteWithSpriteFrameName:@"storageBtnNormalRead.png"];
        ppReadClick = [CCSprite spriteWithSpriteFrameName:@"storageBtnClickRead.png"];
        ppHead = [CCSprite spriteWithSpriteFrameName:@"storageHead.png"];
        ppOutHead = [CCSprite spriteWithSpriteFrameName:@"storageHeadOutBg.png"];
        
        //人物的文本
        ppClickRead = [CCSprite spriteWithSpriteFrameName:@"storageWdClickRead.png"];
        
        //指挥官
        ppType = [CCLabelTTF labelWithString:@"指挥官" fontName:@"Marker Felt" fontSize:12];
        
        //名称
        ppName = [CCLabelTTF labelWithString:@"玩家名称是八个字" fontName:@"Marker Felt" fontSize:10];
        
        //等级
        ppLevel = [CCLabelTTF labelWithString:@"一等上士" fontName:@"Marker Felt" fontSize:10];
        
        //日期
        ppDate = [CCLabelTTF labelWithString:@"2013/07/06 23:12:11" fontName:@"Marker Felt" fontSize:10];
        
        //金币
        ppGold = [CCLabelTTF labelWithString:@"金币 ：" fontName:@"Marker Felt" fontSize:10];
        
        //军需
        ppArmNeed = [CCLabelTTF labelWithString:@"军需 ：" fontName:@"Marker Felt" fontSize:10];
        
        //舰队规模
        ppWarShip = [CCLabelTTF labelWithString:@"舰队规模" fontName:@"Marker Felt" fontSize:10];
        
        //金币数字
        ppGoldNum = [CCLabelTTF labelWithString:@"123456789" fontName:@"Marker Felt" fontSize:10];
        
        //军需数字
        ppArmNeedNum = [CCLabelTTF labelWithString:@"123456789" fontName:@"Marker Felt" fontSize:10];
        
        //舰队规模
        ppWarShipNum = [CCLabelTTF labelWithString:@"20/20" fontName:@"Marker Felt" fontSize:10];
        
        //构造面板的UI
        ppFloor.position = ccp(ppFloor.contentSize.width/2+28,   ppFloor.contentSize.height/2 + 4);
        [self addChild:ppFloor];
        //新建存档背景
        newFloor.position = ccp(newFloor.contentSize.width/2+28, newFloor.contentSize.height/2 + 4);
        [self addChild:newFloor];
        
       
        
        //装饰元件背景
        ppLine = [CCMenuItemSprite itemFromNormalSprite:ppLineNormal selectedSprite:ppLineClick target:self selector:@selector(onPeopleLineButton:)];
        ppLine.position = ccp(ppLine.contentSize.width / 2 +28 , ppFloor.contentSize.height+4-ppLine.contentSize.height/2);
        
        ppClcikRead = [CCMenuItemSprite itemFromNormalSprite:ppReadNormal selectedSprite:ppReadClick target:self selector:@selector(onPeopleClcikReadButton:)];
        ppClcikRead.position = ccp(ppReadNormal.contentSize.width/2+328, ppReadNormal.contentSize.height/2+2);
        
        ppNewSave = [CCMenuItemSprite itemFromNormalSprite:ppNewSaveNormal selectedSprite:ppNewSaveClick target:self selector:@selector(onPeopleNewSaveButton:)];
        ppNewSave.position = ccp(ppNewSaveNormal.contentSize.width/2+204, ppNewSaveNormal.contentSize.height/2+16);
        
        
        //菜单
        menu = [CCMenu menuWithItems:ppLine, ppClcikRead,ppNewSave,nil];
        menu.position = CGPointZero;
        [self addChild:menu];
        
        //点击读取背景
        ppClickRead.position = ccp(ppClickRead.contentSize.width+328, ppClickRead.contentSize.height+2);
        [self addChild:ppClickRead];
        
        ppHead.position = ccp(ppHead.contentSize.width / 2 +28, ppHead.contentSize.height / 2 + 8);
        [self addChild:ppHead];
        ppOutHead.position = ccp(ppOutHead.contentSize.width / 2 +28, ppOutHead.contentSize.height / 2 + 8);
        [self addChild:ppOutHead];
        
        
        //文本
        //指挥官1
        ppType.position = ccp(ppType.contentSize.width/2+88, ppType.contentSize.height/2+46);
        ppType.color = ccc3(255, 255, 255);
        [self addChild:ppType];
        //名称
        ppName.position = ccp(ppName.contentSize.width/2+ 138, ppName.contentSize.height/2+46);
        ppName.color  = ccc3(60, 255, 0);
        [self addChild:ppName];
        //等级
        ppLevel.position = ccp(ppLevel.contentSize.width/2+260, ppLevel.contentSize.height/2+46);
        ppLevel.color  = ccc3(255, 255, 255);
        [self addChild:ppLevel];
        
        //日期
        ppDate.position = ccp(ppDate.contentSize.width/2+326, ppDate.contentSize.height/2+46);
        ppDate.color  = ccc3(0, 255, 255);
        [self addChild:ppDate];
        
        //金币
        ppGold.position = ccp(ppGold.contentSize.width/2+116, ppGold.contentSize.height/2+ 25);
        ppGold.color  = ccc3(255, 255, 255);
        [self addChild:ppGold];
        
        //军需
        ppArmNeed.position = ccp(ppArmNeed.contentSize.width/2+220, ppArmNeed.contentSize.height/2 + 25);
        ppArmNeed.color  = ccc3(255, 255, 255);
        [self addChild:ppArmNeed];
        
        //舰队规模
        ppWarShip.position = ccp(ppWarShip.contentSize.width/2+190, ppWarShip.contentSize.height/2+10);
        ppWarShip.color  = ccc3(255, 255, 255);
        [self addChild:ppWarShip];
        
        //金币数字
        ppGoldNum.position = ccp(ppGoldNum.contentSize.width/2+148, ppGoldNum.contentSize.height/2+25);
        ppGoldNum.color  = ccc3(255, 215, 53);
        [self addChild:ppGoldNum];
        
        //军需数+
        ppArmNeedNum.position = ccp(ppArmNeedNum.contentSize.width/2+254, ppArmNeedNum.contentSize.height/2+25);
        ppArmNeedNum.color  = ccc3(255, 215, 53);
        [self addChild:ppArmNeedNum];
        
        //舰队规模
        ppWarShipNum.position = ccp(ppWarShipNum.contentSize.width/2+246, ppWarShipNum.contentSize.height/2+10);
        ppWarShipNum.color  = ccc3(255, 215, 53);
        [self addChild:ppWarShipNum];
        
        //存档
        ud = [NSUserDefaults standardUserDefaults]; 
        udObject = [ud objectForKey:dataKey]; 
        if(udObject != nil)//使用存档数据
        {
            //抽取玩家信息显示
            [self updateUserItemInfo];
            //显示信息面板
            [self showHaveData];
            //隐藏创建面板
            [self hideNewCreate];
        }
        else//数据不存在，创建新存档并使用
        {
            //隐藏信息面板
            [self hideHaveData];
            //显示创建面板
            [self showNewCreate];
        }
        
    
    }

    
    return self;
}

/**
 UI隐藏已经创建的存档  有数据的
 */
-(void) hideHaveData
{
    //构造面板的UI
    ppFloor.visible =  NO;
    
    //人物
    ppLineNormal.visible =  NO;
    ppLineClick.visible =  NO;
    ppReadNormal.visible =  NO;
    ppReadClick.visible =  NO;
    ppHead.visible =  NO;
    ppOutHead.visible =  NO;
    
    //人物的文本
    ppClickRead.visible =  NO;
    //指挥官
    ppType.visible =  NO;
    
    //名称
    ppName.visible =  NO;
    //等级
    ppLevel.visible =  NO;
    //日期
    ppDate.visible =  NO;
    //金币
    ppGold.visible =  NO;
    //军需
    ppArmNeed.visible =  NO;
    //舰队规模
    ppWarShip.visible =  NO;
    //金币数字
    ppGoldNum.visible =  NO;
    //军需数字
    ppArmNeedNum.visible =  NO;
    //舰队规模
    ppWarShipNum.visible =  NO;
    
    //装饰元件背景
    ppLine.visible =  NO;
    ppClcikRead.visible =  NO;
}

/**
 UI隐藏没有存档    要新建存档
 */
-(void) hideNewCreate
{
    //新建存档背景
    newFloor.visible =  NO;
    ppNewSaveNormal.visible = NO;
    ppNewSaveClick.visible = NO;
}

/**
 UI显示已经创建的存档  有数据的
 */
-(void) showHaveData
{
    //构造面板的UI
    ppFloor.visible =  YES;
    
    //人物
    ppLineNormal.visible =  YES;
    ppLineClick.visible =  YES;
    ppReadNormal.visible =  YES;
    ppReadClick.visible =  YES;
    ppHead.visible =  YES;
    ppOutHead.visible =  YES;
    
    //人物的文本
    ppClickRead.visible =  YES;
    //指挥官
    ppType.visible =  YES;
    
    //名称
    ppName.visible =  YES;
    //等级
    ppLevel.visible =  YES;
    //日期
    ppDate.visible =  YES;
    //金币
    ppGold.visible =  YES;
    //军需
    ppArmNeed.visible =  YES;
    //舰队规模
    ppWarShip.visible =  YES;
    //金币数字
    ppGoldNum.visible =  YES;
    //军需数字
    ppArmNeedNum.visible =  YES;
    //舰队规模
    ppWarShipNum.visible =  YES;
    
    //装饰元件背景
    ppLine.visible =  YES;
    ppClcikRead.visible =  YES;
}

/**
 UI显示没有存档    要新建存档
 */
-(void) showNewCreate
{
    newFloor.visible =  YES;
    ppNewSaveNormal.visible = YES;
    ppNewSaveClick.visible = YES;
}


-(void) updateUserItemInfo
{
    UserData* userData = [NSKeyedUnarchiver unarchiveObjectWithData:udObject];
    //玩家名字
    [ppName setString:[NSString stringWithFormat:@"%@", userData.userName]];
    
    //等级表示,查等级表
    LevelUpInfo* levelInfo = [[LevelUpInfoMgr sharedManager] getInfoById:userData.level];
    [ppLevel setString:[NSString stringWithFormat:@"%@", levelInfo.name]];
    
    //最后存档时间
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy年MM月dd日 HH小时mm分ss秒"];
    NSString * na = [df stringFromDate:userData.date];
    [ppDate setString:[NSString stringWithFormat:@"%@", na]];
    [df release];
    df = nil;
    
    //军需（钱）
    [ppGoldNum setString:[NSString stringWithFormat:@"%d", userData.money]];
    //战功（经验）
    [ppArmNeedNum setString:[NSString stringWithFormat:@"%d", userData.exp]];
    //舰船数量(舰队规模/最大舰队规模)
    //舰队规模=出战战舰消耗点数和（cost）
    //最大舰队规模=16+等级×2（Cost上限额）
    int cost = 0;
    int costMax = 16 + userData.level * 2;
    for (ShipVo* shipVo in userData.fightShipArray) 
    {
        ShipInfo* info = [[ShipInfoMgr sharedManager] getInfoById:shipVo.shipId];
        if(info != nil)
        {
            cost += info.fleetCost;
        }
    }
    [ppWarShipNum setString:[NSString stringWithFormat:@"%d/%d", cost, costMax]];
}


/**
 处理删除存档
 @param sender  事件发出者
 */
-(void) onPeopleLineButton:(id)sender
{
    NSAssert([self.parent isKindOfClass:[StorageScene class]], @"not a StorageScene!");
    StorageScene* storageLayer = (StorageScene*)self.parent;
    
    StorageWindowItem* windowItem = [StorageWindowItem windowItemWithTarget:self ok:@selector(onDeletePeopleSaveData)];
    //        windowItem.position = ccp(windowItem.contentSize.width/2, windowItem.contentSize.height/2+65);
    windowItem.position = ccp(windowItem.contentSize.width/2, windowItem.contentSize.height/2);
    [storageLayer addChild:windowItem];
    windowItem.visible =  YES;
}

-(void) onDeletePeopleSaveData
{
    //清除存档数据
    [ud removeObjectForKey:dataKey];
    
    //隐藏信息面板
    [self hideHaveData];
    
    //显示创建面板
    [self showNewCreate];
}

/**
 处理读取按钮得点击
 @param sender  事件发出者
 */
-(void) onPeopleClcikReadButton:(id)sender;
{
    //载入存档，并从磁盘序列化数据
    [[UnitProxy sharedManager] loadUserDataByKey:dataKey];
    
    //跳转界面
    CCTransitionFade* trans = [CCTransitionFade transitionWithDuration:1.0 scene:[StartScene scene]];
	[[CCDirector sharedDirector] replaceScene: trans];
}



/**
 处理新建存档按钮点击
 @param sender  事件发出者
 */
-(void) onPeopleNewSaveButton:(id)sender;
{
    //创建一个新存档数据体,并将初始值保存到磁盘
    [[UnitProxy sharedManager] createUserDataByKey:dataKey];
    
    //跳转界面
    CCTransitionFade* trans = [CCTransitionFade transitionWithDuration:1.0 scene:[StartScene scene]];
	[[CCDirector sharedDirector] replaceScene: trans];
}

@end

@implementation StorageWindowItem

+(id) windowItemWithTarget:(id)target ok:(SEL)okSelector
{
    return [[[StorageWindowItem alloc] initItemWith:target ok:okSelector] autorelease];
}

-(id) initItemWith:(id)target ok:(SEL)okSelector
{
    if((self = [super init]))
    {
        _target = target;
        _okSelector = okSelector;
        [self initBackGround];
        CCSprite* sureNormal = [CCSprite spriteWithSpriteFrameName:@"battleBtnNormal.png"];
        CCSprite* sureClick = [CCSprite spriteWithSpriteFrameName:@"battleBtnClick.png"];
        CCSprite* cancelNormal = [CCSprite spriteWithSpriteFrameName:@"battleBtnNormal.png"];
        CCSprite* cancelClick = [CCSprite spriteWithSpriteFrameName:@"battleBtnClick.png"];
        
        CCSprite* sureBg = [CCSprite spriteWithSpriteFrameName:@"storageWdSure.png"];
        CCSprite* cancelBg = [CCSprite spriteWithSpriteFrameName:@"storageWdCancel.png"];
        
        CCMenuItemSprite *menuSure;  //确定
        CCMenuItemSprite *menuCancel;  //取消
        CCMenu*	menu;
        
        //装饰元件背景
        //X轴 镜像反转
        [sureNormal setFlipX:YES];
        [sureClick setFlipX:YES];
        menuSure = [CCMenuItemSprite itemFromNormalSprite:sureNormal selectedSprite:sureClick target:self selector:@selector(onWindowSureButton:)];
        menuSure.position = ccp(menuSure.contentSize.width / 2 +128 , 180-menuSure.contentSize.height/2);
        
        menuCancel = [CCMenuItemSprite itemFromNormalSprite:cancelNormal selectedSprite:cancelClick target:self selector:@selector(onWindowCancelButton:)];
        menuCancel.position = ccp(menuCancel.contentSize.width / 2 +248 ,180- menuCancel.contentSize.height/2);
        
        
        
        //菜单
        menu = [CCMenu menuWithItems:menuSure, menuCancel,nil];
        menu.position = CGPointZero;
        [self addChild:menu];
        
        sureBg.position = ccp(menuSure.contentSize.width / 2 +128, 180-(menuSure.contentSize.height/2 + sureBg.contentSize.height)/2);
        [self addChild:sureBg];
        
        cancelBg.position = ccp(menuSure.contentSize.width / 2 +248, 180-(menuSure.contentSize.height/2 + cancelBg.contentSize.height)/2);
        [self addChild:cancelBg];
        
    }
    return self;

}

-(void) initBackGround
{
    //画有一个背景图  
    ccColor4B  color = {20,20,30,204};
	CCLayerColor* layer = [CCLayerColor layerWithColor:color width:480 height:320];
    [self addChild:layer];
    

    
    CCSprite* lineBg1 = [CCSprite spriteWithSpriteFrameName:@"storageLineBg.png"];
    CCSprite* lineBg2 = [CCSprite spriteWithSpriteFrameName:@"storageLineBg.png"];
    lineBg1.position = ccp(lineBg1.contentSize.width/2+50, 160-lineBg1.contentSize.height/2-20);
    [self addChild:lineBg1];
    
    lineBg2.position = ccp(lineBg2.contentSize.width/2+50, 160-lineBg2.contentSize.height/2+25);
    [self addChild:lineBg2];
}

/**
 弹窗确定按钮
 */
-(void) onWindowSureButton:(id)sender
{
    //执行回调方法
    [_target performSelector:_okSelector];
    
    //从父对象上移除
    [self.parent removeChild:self cleanup:YES];
}

-(void) onWindowCancelButton:(id)sender
{
    //从父对象上移除
    [self.parent removeChild:self cleanup:YES];
}



@end


@implementation StorageScene

+(CCScene *) scene
{
    // 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	StorageScene *layer = [StorageScene node];
    
	[scene addChild: layer];
    
	return scene;
}

-(id) init
{
    if( (self=[super init]))
    {
        //缓冲图片文件
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"UIStorage_480_320.plist"];
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"UIBattleSettle_480_320.plist"];
        
        // ask director the the window size
        size = [[CCDirector sharedDirector] winSize];
        
        //给全局变量赋值
        extern NSString* USERDATA_KEY1;
        USERDATA_KEY1 = @"SpaceStorm1";
        
        extern NSString* USERDATA_KEY2;
        USERDATA_KEY2 = @"SpaceStorm2";
        
        extern NSString* USERDATA_KEY3;
        USERDATA_KEY3 = @"SpaceStorm3";
        
        //初始化背景
        [self initBackGround];
        
        //初始化标题头
        [self initHead];
        
        //存档的item类
        storageItem1 = [StorageItem itemWithIndex:1];
        storageItem1.position = ccp(storageItem1.contentSize.width/2, size.height - storageItem1.contentSize.height/2 -134);
        [self addChild:storageItem1];

        storageItem2 = [StorageItem itemWithIndex:2];
        storageItem2.position = ccp(storageItem2.contentSize.width/2, size.height - storageItem2.contentSize.height/2 -210);
        [self addChild:storageItem2];
        
        storageItem3 = [StorageItem itemWithIndex:3];
        storageItem3.position = ccp(storageItem3.contentSize.width/2, size.height - storageItem3.contentSize.height/2 -286);
        [self addChild:storageItem3];
    }
    return self;
}

/**
 UI背景
 */
-(void) initBackGround
{
    CCSprite* backGround = [CCSprite spriteWithSpriteFrameName:@"storageBg.jpg"];
    backGround.position = ccp(size.width / 2 , size.height / 2);
    [self addChild:backGround];
}

/**
 UI标题头
 */
-(void) initHead
{
    //标题左边
    CCSprite *headLeft = [CCSprite spriteWithSpriteFrameName:@"storageLeftWenBg.png"];
    //标题右边
    CCSprite *headRight = [CCSprite spriteWithSpriteFrameName:@"storageLeftWenBg.png"];
    //标题背景
    CCSprite *headBg = [CCSprite spriteWithSpriteFrameName:@"storageFontBg.png"];
    //标题文字
    CCSprite *titleBg = [CCSprite spriteWithSpriteFrameName:@"storageReadSaveBg.png"];
    //标题线条
    CCSprite *titleLineBg = [CCSprite spriteWithSpriteFrameName:@"storageLineBg2.png"];
    
    //X轴 镜像反转
    [headLeft setFlipX:YES];
    titleLineBg.scaleX = (size.width - 150)/titleLineBg.contentSize.width;
    titleLineBg.position = ccp(36+(size.width-titleLineBg.contentSize.width)/2, size.height - headLeft.contentSize.height+4);
    [self addChild:titleLineBg];
    
    headBg.position = ccp((size.width-headLeft.contentSize.width)/2+60, size.height - headBg.contentSize.height/2);
    [self addChild:headBg];
    
    headLeft.position = ccp(headLeft.contentSize.width/2+16, size.height - headLeft.contentSize.height/2);
    [self addChild:headLeft];
    
    headRight.position = ccp(size.width - headRight.contentSize.width/2-16 , headLeft.position.y);
    [self addChild:headRight];
    titleBg.position = ccp((size.width  - titleBg.contentSize.width)/2+titleBg.contentSize.width/2, size.height - titleBg.contentSize.height/2-3);
    [self addChild:titleBg];
    
    //内背景层
    BubbleSprite *innerBg = [BubbleSprite spriteWithFrameName:@"storageJiuInnerBg.png" size:CGSizeMake(452, 272) leftCap:10 topCap:10];
    //    innerBg.anchorPoint = ccp(0, 0); //设置图片的锚点在左左下角
    innerBg.position = ccp(15+innerBg.contentSize.width/2, size.height - 41 - innerBg.contentSize.height/2);
    [self addChild:innerBg];
    
    //外框背景
    BubbleSprite *inOutBg = [BubbleSprite spriteWithFrameName:@"storageJiuOutBg.png" size:CGSizeMake(442, 262) leftCap:4 topCap:4];
    inOutBg.position = ccp(20+inOutBg.contentSize.width/2, size.height - 46 - inOutBg.contentSize.height/2);
    [self addChild:inOutBg];
}


- (void) dealloc
{
    [super dealloc];
}

@end
